import token from "@/utils/token";
// import config2 from "../../private.config";
/**
 * 手机号码脱敏
 * @param {*} phone 手机号
 */
export const insensitivePhone = (phone) => {
  return phone.replace(/(\d{3})\d*(\d{4})/, "$1****$2");
};

/**
 * @description 格式化字符串，转换成xxxx年xx月xx日 hh:mm:ss, 若在时间在今年则省略年份 xx月xx日 hh:mm:ss
 * @param dateString 日期时间字符串
 */
export const formTime = (dateString, needSec = true) => {
  if (dateString == null || dateString == "") {
    return "";
  }
  let date =
    dateString instanceof Date
      ? dateString
      : new Date(Date.parse(dateString.replace(/-/g, "/")));

  let currentDate = new Date();
  let temp = `${
    date.getFullYear() == currentDate.getFullYear()
      ? ""
      : `${date.getFullYear()}年`
  }${date.getMonth() + 1}月${date.getDate()}日 ${
    date.getHours() < 10 ? `0${date.getHours()}` : date.getHours()
  }:${date.getMinutes() < 10 ? `0${date.getMinutes()}` : date.getMinutes()}${
    needSec
      ? `:${
          date.getSeconds() < 10 ? `0${date.getSeconds()}` : date.getSeconds()
        }`
      : ""
  }`;
  return temp;
};

/**
 * @description 获取倒计时剩余的天、时、分、秒
 * @param time 时间节点
 */
export const showtime = (time) => {
  let nowtime = new Date(), // 获取当前时间
    endtime = new Date(Date.parse(time.replace(/-/g, "/"))); // 定义结束时间
  let lefttime = endtime.getTime() - nowtime.getTime(); // 距离结束时间的毫秒数
  if (Math.floor(lefttime / (1000 * 60 * 60 * 24)) < 0) {
    return {
      day: 0, // 计算天数
      hour: 0, // 计算小时数
      min: 0, // 计算分钟数
      sec: 0, // 计算秒数
    };
  }
  return {
    day: Math.floor(lefttime / (1000 * 60 * 60 * 24)), // 计算天数
    hour: Math.floor((lefttime / (1000 * 60 * 60)) % 24), // 计算小时数
    min: Math.floor((lefttime / (1000 * 60)) % 60), // 计算分钟数
    sec: Math.floor((lefttime / 1000) % 60), // 计算秒数
  };
};

/**
 * @description 格式化数字，可以选择性保留小数点位数，每隔三位数加一逗号
 * @param number 数字
 */
export const formatNumber = (number) => {
  if (number == null || isNaN(number)) return "";
  let text = number.toString().split(".");
  return (
    text[0].replace(/(\d)(?=(?:\d{3})+$)/g, "$1,") +
    (text.length > 1 ? "." + text[1] : "")
  );
};

/**
 * @description 格式化数字，以万为单位，以万或亿为单位
 * @param number 数字
 */
export const formatNumberWithUnit = (number, n = 2) => {
  if (number === "" || number == null || isNaN(number)) return "";
  if (number < 10000) {
    return number.toFixed(n);
  } else if (number >= 10000 && number < 100000) {
    return `${toFixedDigit(number / 10000, 3)}万`;
  } else if (number >= 100000 && number < 1000000) {
    return `${toFixedDigit(number / 10000, 2)}万`;
  } else if (number >= 1000000 && number < 10000000) {
    return `${toFixedDigit(number / 10000, 1)}万`;
  } else if (number >= 10000000 && number < 100000000) {
    return `${parseInt(number / 10000)}万`;
  } else if (number >= 100000000 && number < 1000000000) {
    return `${toFixedDigit(number / 100000000, 3)}亿`;
  } else if (number >= 1000000000 && number < 10000000000) {
    return `${toFixedDigit(number / 100000000, 2)}亿`;
  } else if (number >= 10000000000 && number < 100000000000) {
    return `${toFixedDigit(number / 100000000, 1)}亿`;
  } else if (number >= 100000000000) {
    return `${parseInt(number / 100000000)}亿`;
  }
};

/**
 * @description 不四舍五入取小数
 * @param num 数字
 * @param n 小数点位数
 */
export const toFixedDigit = (num, n) => {
  // 保留n位
  if (typeof num != "number") {
    return false;
  }

  num = num.toString();
  var result = "";
  var zeroResult = function (n) {
    var zero = "";
    for (var i = 0; i < n; i++) {
      zero += "0";
    }
    return zero;
  };
  if (num % 1 == 0) {
    // 整数
    result = num + "." + zeroResult(n);
  } else {
    // 小数
    var num1 = num.split(".");
    if (num1[1].length < n) {
      result = num1[0] + "." + num1[1] + zeroResult(n - num1[1].length);
    } else {
      result = num1[0] + "." + num1[1].substring(0, n);
    }
  }
  return result;
};

/**
 * @description 当前时间和传入的时间比较，超过返回true，未超过返回false
 * @param time 时间
 */
export const overTime = (time) => {
  var result = new Date() - new Date(time.replace(/-/g, "/")); //判断结束时间减去当前时间 ，如果当前时间大于0则为True
  return result > 0 ? true : false;
  // var myDate = new Date();
  // var now = myDate.valueOf();
  // var time = new Date(time).valueOf();
  // if (now >= time) {
  //   return true;
  // } else {
  //   return false;
  // }
};

// 根据token判断是否需要登录
export const isLogin = (isBidding = true) => {
  if (token.get()) {
    return true;
  }
  let url =
    process.env.NODE_ENV === "development"
      ? config2.toLogin.dev
      : config2.toLogin.pro;
  window.open(`${url}?rUrl=${window.location.href}`, "_self");
  return false;
};

/**
 * 函数防抖
 */
export function debounce(fn, delay) {
  // 记录上一次的延时器
  var timer = null;
  var delay = delay || 200;
  return function () {
    var args = arguments;
    var that = this;
    // 清除上一次延时器
    clearTimeout(timer);
    timer = setTimeout(function () {
      fn.apply(that, args);
    }, delay);
  };
}

// 去除首尾空格
export function trimStr(str) {
  return str.replace(/(^\s*)|(\s*$)/g, "");
}

/**
 * 内部方法根据时间戳创建日期
 * @param {*} unixTimestamp
 */
const _createDate = (unixTimestamp) => {
  unixTimestamp = unixTimestamp || new Date().getTime();
  unixTimestamp =
    (unixTimestamp + "").length == 10 ? unixTimestamp * 1000 : unixTimestamp;
  return new Date(unixTimestamp);
};

/**
 * 时间戳格式化时间
 * @param {*} unixTimestamp 时间戳
 * @param {*} formatTime 格式化时间的格式
 */
export const unixTimestampFormatTime = (unixTimestamp, formatTime) => {
  let date =
    typeof unixTimestamp === "number"
      ? _createDate(unixTimestamp)
      : new Date(unixTimestamp.replace("-", "/"));
  let year = date.getFullYear(),
    month = formatNumber(date.getMonth() + 1),
    day = formatNumber(date.getDate()),
    hour = formatNumber(date.getHours()),
    minutes = formatNumber(date.getMinutes()),
    second = formatNumber(date.getSeconds()),
    milliseconds = formatNumber(date.getMilliseconds());
  return formatTime
    .replace("yyyy", year)
    .replace("MM", month)
    .replace("dd", day)
    .replace("HH", hour)
    .replace("mm", minutes)
    .replace("ss", second)
    .replace("SSS", milliseconds);
};

// 时间格式是否补0
const formatNumbers = (n) => {
  n = n.toString();
  return n[1] ? n : "0" + n;
};

// 根据时间戳、返回模板返回对应的格式
export const timeFormat = ({
  val = 0,
  format = "DD:HH:mm:ss",
  isSubstitute = false,
  isCut = false,
}) => {
  if (val <= 0) return "";
  // 计算秒单位
  const secondsFormula = 1000 * 60;
  const minutesFormula = secondsFormula * 60;
  const hoursFormula = minutesFormula * 24;
  // 计算天数
  let byDayFormula = Math.floor(val / hoursFormula) || 0;
  // 计算小时数
  let byHoursFormula =
    Math.floor(val / minutesFormula - byDayFormula * 24) || 0;
  // 计算分钟数
  let byMinutes =
    Math.floor(
      val / secondsFormula - byDayFormula * 24 * 60 - byHoursFormula * 60
    ) || 0;
  // 计算秒数
  let bySeconds =
    Math.floor(
      (val -
        byDayFormula * hoursFormula -
        byHoursFormula * minutesFormula -
        byMinutes * secondsFormula) /
        1000
    ) || 0;
  if (
    byDayFormula === 0 &&
    byHoursFormula === 0 &&
    byMinutes === 0 &&
    bySeconds === 0
  ) {
    return "";
  }
  // 获取天的mack
  let temp = format;
  //DD天HH小时mm分ss秒
  let dayuUnit = temp.match(/DD([\s\S]*?)HH/);
  let hoursUnit = temp.match(/HH([\s\S]*?)mm/);
  let minutesUnit = temp.match(/mm([\s\S]*?)ss/);
  let secondsUnit = temp.match(/ss(\S*)/);
  dayuUnit ? (dayuUnit = dayuUnit[1]) : (dayuUnit = "");
  hoursUnit ? (hoursUnit = hoursUnit[1]) : (hoursUnit = "");
  minutesUnit ? (minutesUnit = minutesUnit[1]) : (minutesUnit = "");
  secondsUnit ? (secondsUnit = secondsUnit[1]) : (secondsUnit = "");
  if (isSubstitute) {
    byDayFormula = formatNumbers(byDayFormula);
    byHoursFormula = formatNumbers(byHoursFormula);
    byMinutes = formatNumbers(byMinutes);
    bySeconds = formatNumbers(bySeconds);
  }
  let tempText = format
    .replace("DD", byDayFormula)
    .replace("HH", byHoursFormula)
    .replace("mm", byMinutes)
    .replace("ss", bySeconds);

  (byDayFormula === 0 || byDayFormula === "00") &&
    (tempText = tempText.replace(`${byDayFormula}${dayuUnit}`, ""));
  (byHoursFormula === 0 || byHoursFormula === "00") &&
    (tempText = tempText.replace(`${byHoursFormula}${hoursUnit}`, ""));
  (byMinutes === 0 || byMinutes === "00") &&
    (tempText = tempText.replace(`${byMinutes}${minutesUnit}`, ""));
  (bySeconds === 0 || bySeconds === "00") &&
    (tempText = tempText.replace(`${bySeconds}${secondsUnit}`, ""));
  if (isCut) {
    if (parseFloat(byDayFormula) > 0) {
      tempText = tempText.replace(`${byMinutes}${minutesUnit}`, "");
      tempText = tempText.replace(`${bySeconds}${secondsUnit}`, "");
    } else if (
      parseFloat(byDayFormula) <= 0 &&
      parseFloat(byHoursFormula) > 0
    ) {
      tempText = tempText.replace(`${bySeconds}${secondsUnit}`, "");
    }
  }
  return tempText;
};
// 默认验证码集合
const codeData = [
  "a",
  "b",
  "c",
  "d",
  "e",
  "f",
  "g",
  "h",
  "i",
  "j",
  "k",
  "l",
  "m",
  "n",
  "o",
  "p",
  "q",
  "r",
  "s",
  "t",
  "u",
  "v",
  "w",
  "x",
  "y",
  "z",
  "A",
  "B",
  "C",
  "D",
  "E",
  "F",
  "G",
  "H",
  "I",
  "J",
  "K",
  "L",
  "M",
  "N",
  "O",
  "P",
  "Q",
  "R",
  "S",
  "T",
  "U",
  "V",
  "W",
  "X",
  "Y",
  "Z",
  "1",
  "2",
  "3",
  "4",
  "5",
  "6",
  "7",
  "8",
  "9",
  "0",
];
// 验证码随机
const randomNum = (min, max) => {
  max = max + 1;
  return Math.floor(Math.random() * (max - min) + min);
};
// 随机生成验证码字符串
export const makeCode = (data = codeData, len = 4) => {
  let identifyCode = "";
  for (let i = 0; i < len; i++) {
    identifyCode += data[randomNum(0, data.length - 1)];
  }
  return identifyCode;
};

export const getStatusText = (val) => {
  let title = "";
  switch (val) {
    case 0:
      title = "未接收";
      break;
    case 1:
      title = "已接收";
      break;
    case 2:
      title = "已拒绝";
      break;
    case 3:
      title = "已取消";
      break;
    default:
      title = "未接收";
      break;
  }
  return title;
};

export const getPushStatusText = (val) => {
  let title = "";
  switch (val) {
    case 0:
      title = "未处理";
      break;
    case 1:
      title = "处理中";
      break;
    case 2:
      title = "成功";
      break;
    case 3:
      title = "失败";
      break;
    default:
      title = "未处理";
      break;
  }
  return title;
};

export const getAuthStatusText = (type, val) => {
  let title = "";
  if (type === 1) {
    switch (val) {
      case 0:
        title = "未认证";
        break;
      case 1:
        title = "认证中";
        break;
      case 2:
        title = "认证成功";
        break;
      case 3:
        title = "认证失败";
        break;
      default:
        title = "-";
        break;
    }
  } else {
    title = "认证成功";
  }
  return title;
};

export const getDomainStatusText = (val) => {
  let title = "";
  switch (val) {
    case 0:
      title = "未处理";
      break;
    case 1:
      title = "处理中";
      break;
    case 2:
      title = "成功";
      break;
    case 3:
      title = "失败";
      break;
    default:
      title = "未处理";
      break;
  }
  return title;
};


